package cn.lingyangwl.framework.knife4j.micro.servlet;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.Api;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 *
 * @author shenguangyang
 */
@Configuration
@EnableOpenApi
@EnableKnife4j
public class Knife4jConfig {
    @Value("${knife4j.enable:false}")
    private Boolean enable;

    @Resource
    private PcKnife4jApiInfoProperties pcKnife4JApiInfoProperties;

    @Bean //配置docket以配置Swagger具体参数
    @ConditionalOnMissingBean
    public Docket docket(Environment environment,
                         List<RequestParameter> globalRequestParameters,
                         List<Response> globalResponseMessage) {
        if (globalRequestParameters == null) {
            globalRequestParameters = new ArrayList<>();
        }
        if (globalResponseMessage == null) {
            globalResponseMessage = new ArrayList<>();
        }
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .globalRequestParameters(globalRequestParameters)
                // 添加全局响应状态码
                .globalResponses(HttpMethod.GET, globalResponseMessage)
                .globalResponses(HttpMethod.POST, globalResponseMessage)
                .globalResponses(HttpMethod.DELETE, globalResponseMessage)
                .globalResponses(HttpMethod.PUT, globalResponseMessage)

                // 配置是否启用Swagger，如果是false，在浏览器将无法访问
                .enable(enable)
                // 以下是一组的
                // 通过.select()方法，去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                // 配置如何通过path过滤,即这里只扫描请求以/api开头的接口
                // .paths(PathSelectors.ant("/api/**"))
                .build();
    }

    /**
     * 项目信息
     */
    private ApiInfo apiInfo() {
        PcKnife4jApiInfoProperties.Contact contact = pcKnife4JApiInfoProperties.getContact();
        return new ApiInfoBuilder().title(pcKnife4JApiInfoProperties.getTitle())
                .description(pcKnife4JApiInfoProperties.getDescription())
                .contact(new Contact(contact.getName(), contact.getUrl(), contact.getEmail()))
                .version(pcKnife4JApiInfoProperties.getVersion())
                .build();
    }

    /**
     * 生成全局通用参数
     */
    @Bean
    @ConditionalOnMissingBean
    public List<RequestParameter> globalRequestParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder()
                .name("x-access-token")
                .description("令牌")
                .required(false)
                .in(ParameterType.HEADER)
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("Equipment-Type")
                .description("产品类型")
                .required(false)
                .in(ParameterType.HEADER)
                .build());
        return parameters;
    }

    /**
     * 生成通用响应信息
     */
    @Bean
    @ConditionalOnMissingBean
    public List<Response> globalResponseMessage() {
        //添加全局响应状态码
//        List<Response> responseMessageList = new ArrayList<>();
//        Arrays.stream(ResultCode.values()).forEach(resultEnum -> {
//            responseMessageList.add(
//                    new ResponseBuilder()
//                            .code(String.valueOf(resultEnum.getCode()))
//                            .description(resultEnum.getMsg())
//                            .build()
//            );
//        });
//        return responseMessageList;
        return new ArrayList<>();
    }

    /**
     * 解决springboot 2.7.2 整合swagger 3, 启动报错问题
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(
                    List<T> mappings) {
                List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    assert field != null;
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}
